package com.kehao.leetcode.jzoffer;

import org.junit.Test;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/7/7 13:38
 */
public class JZSolution051 {
    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int max = 0;
    public int maxPathSum(TreeNode root) {
        if(root==null) return 0;
        if(root.left==null&&root.right==null){
            return root.val;
        }
        max = root.val;
        maxHalfSum(root);
        return max;
    }

    private int maxHalfSum(TreeNode root){
        if(root==null) return 0;
        int left = maxHalfSum(root.left);
        int right = maxHalfSum(root.right);
        int value = Integer.max(left,right)+ root.val;
        if(value< root.val) value = root.val;
        int newMax = 0;
        if(left>0){
            newMax+=left;
        }
        if(right>0){
            newMax+=right;
        }
        max = Integer.max(max,newMax+root.val);
        return value;
    }

    @Test
    public void test01(){
        TreeNode root = buildTree(new Integer[]{2,-1});
        int result = maxPathSum(root);
        System.out.println(result);
    }

    private TreeNode buildTree(Integer[] treeArray){
        TreeNode[] treeNodeList = new TreeNode[treeArray.length];
        for (int i = 0; i < treeArray.length; i++) {
            if(treeArray[i]!=null){
                treeNodeList[i] = new TreeNode(treeArray[i]);
            }
        }
        for (int i = 0; i < treeNodeList.length/2; i++) {
            if(i*2+1<treeNodeList.length){
                treeNodeList[i].left = treeNodeList[i*2+1];
            }
            if(i*2+2<treeNodeList.length){
                treeNodeList[i].right = treeNodeList[i*2+2];
            }
        }
        return treeNodeList[0];
    }

}
